<!--
	作者：Sariay
	时间：2018-09-25
	描述：There may be a bug, but don't worry, QiLing(器灵) says that it can work normally!
-->
<!DOCTYPE html>
<html class="html-loading">
		

<head><meta name="generator" content="Hexo 3.9.0">
	<!-- hexo-inject:begin --><!-- hexo-inject:end --><meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <title>
    
      进程、线程及共享内存学习笔记 | Sunow&#39;s Club
    
  </title>
  <meta name="author" content="sunowsir">
  <meta name="keywords" content>
  <meta name="description" content="This is Sunowsir&#39;s club.">
	<!-- favicon -->
  <link rel="shortcut icon" href="/img/favicon.ico">

  <!-- css -->
  <link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="/css/Annie.css">
  
  <!-- jquery -->
	<script src="/js/jquery.min.js"></script>

  <!-- leancloud -->
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
<script src="/js/leancloud.js"></script><!-- hexo-inject:begin --><!-- hexo-inject:end -->
</head>
	<body>
        <!-- hexo-inject:begin --><!-- hexo-inject:end --><!--动态线条背景-->
        <script type="text/javascript"
        color="220,220,220" opacity='0.7' zIndex="-2" count="200" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js">
        </script>
		<!-- Preloader -->

	<div id="preloader">
		<div class="pre-container">
			
				<div class="spinner">
					<div class="double-bounce1"></div>
					<div class="double-bounce2"></div>
				</div>
						
		</div>
	</div>


<!-- header -->
<header class="fixbackground" data-img-mode="random" data-normal-src="/img/1.jpg" data-random-max="110" data-random-src="https://sariay.github.io/Random-img/">
	<div class="mask">
		<!-- Logo and navigation -->
		<div class="h-header">
			<div id="logo">
				<a href="/">
						
						<img src="/img/logo.png" alt="Logo">
					
				</a>
			</div>
			
			<div id="navigation-show">
				<ul>
	
		<li class="menu-home">
			<a href="/" class="menu-item-home">主页</a>
		</li>
	
		<li class="menu-archive">
			<a href="/archives" class="menu-item-archive">归档</a>
		</li>
	

	
		<li class="menu-search">
			<a href="javascript:;" class="popup-trigger">搜索</a>
		</li>
	
</ul>
			</div>				
		</div>

		<!-- motto -->
		<div class="h-body">	
			
				<p class="motto"></p>
			
		</div>
		
		<!-- others: such as time... -->			
		<div class="h-footer">
			<a href="javascript:;" id="read-more"><i class="fa fa-angle-double-down" aria-hidden="true"></i>
			</a>

			
				<!-- 
	This is only a demo, please go to "https://time.is" to set your city time! 
-->
<style type="text/css">
	.header-date {
		font-size: 1.6rem;
		color: #fff;
		position: absolute;
		bottom: 5px;
		right: 1rem;
		writing-mode: tb-rl;
	}	
	
	.header-date a {
		border-bottom: none;
	}

	@media only screen and (max-width: 768 ) {
		.header-date {
			font-size: 1rem;
		}			
	}
</style>
<div class="header-date">
	<a href="https://time.is/Beijing" id="time_is_link" rel="nofollow" ></a>
	<span id="Beijing_z43d"></span>
</div>
<script src="//widget.time.is/zh.js"></script>
<script>
	time_is_widget.init({
		Beijing_z43d:{
			template:"DATE", 
			date_format:"year年 monthname dnum日"
		}
	});
</script>
			
		</div>
	</div>
</header>

<div id="navigation-hide">
	<!-- Progress bar -->
	<div id="progress-bar"></div>

	<!-- Progress percent -->
	<div id="progress-percentage"><h1>0.0%</h1></div>

	<div class="toc-switch"><span class="switch-button">目录</span></div>

	<!-- Page title -->
	<p>
		
			当前文章&nbsp;:&nbsp;《进程、线程及共享内存学习笔记》
		
	</p>

	<!-- Nav trigger for navigation-H-->
	<a class="nav-trigger"><span></span></a>
</div>

<!-- Navigation in div(id="navigation-H") -->
<nav class="nav-container" id="cd-nav">
	<div class="nav-header">
		<h3>Navigation</h3>
		<a href="javascript:;" class="nav-close"></a>
	</div>
	<div class="nav-body">
		<ul>
	
		<li class="menu-home">
			<a href="/" class="menu-item-home">主页</a>
		</li>
	
		<li class="menu-archive">
			<a href="/archives" class="menu-item-archive">归档</a>
		</li>
	

	
		<li class="menu-search">
			<a href="javascript:;" class="popup-trigger">搜索</a>
		</li>
	
</ul>
	</div>
	<div class="nav-footer">
		<ul>
	
		<li>
			<a href="http://github.com/sunowsir" target="_blank">
				<i class="fa fa-github"></i>
			</a>
		</li>
			
</ul>

	</div>
</nav>
			
		<!--main-->
		<main>
			<!--
	时间：2018-11-17
	描述：
		插件名称：katelog.min.js
		插件作者：KELEN
		插件来源: https://github.com/KELEN/katelog
-->

	
		<div class="layout-toc">
			<div id="layout-toc">
				<div class="k-catelog-list" id="catelog-list" data-title="文章目录"></div>
			</div>
		</div>

		
		<script src="/plugin/toc/katelog.min.js"></script>

		
	 

<div class="layout-post">
	<div id="layout-post">
	<div class="article-title">
		<i class="fa fa-paper-plane-o" aria-hidden="true"></i>
		
	<a href="/2019/09/02/进程、线程及共享内存学习笔记/" itemprop="url">
		进程、线程及共享内存学习笔记
	</a>

	</div>

	<div class="article-meta">
		<span>
			<i class="fa fa-calendar"></i>
			


	发布于

	<a href="/2019/09/02/进程、线程及共享内存学习笔记/" itemprop="url">
		<time datetime="2019-09-02T08:40:51.000Z" itemprop="datePublished">
	  		2019-09-02
	  </time>
	</a>
	&nbsp;





			




	更新于

	<a href="/2019/09/02/进程、线程及共享内存学习笔记/" itemprop="url">
		<time datetime="2019-09-02T08:40:51.000Z" itemprop="dateUpdated">
	  		2019-09-16
	  </time>
	</a> 



		</span>
		<span>
			<i class="fa fa-tags"></i>
			
	
		<a href="/tags/note/" class=" ">
			note
		</a>
	
		
		</span>
		
		



	</div>

	<div class="article-content" id="article-content">
		<h2>进程、线程及共享内存学习笔记</h2>
<blockquote>
<p>系统环境：deepin Linux，语言环境：Linux C
欢迎大家转载，转载请注明出处，谢谢！</p>
</blockquote>
<ol>
<li>
<p>理论基础：</p>
<ul>
<li>进程：计算机上每个执行的活动，运行一个可执行程序是一个进程，打开一个软件是一个进程，打开一个终端是一个进程等等。</li>
<li>多进程：为了充分利用计算机资源产生了多进程的执行方式。通俗来讲就是在同一时间做多个事情，从而可以充分利用计算机资源还可以提高程序的执行效率。在创建一个新的子进程后，子进程会会获得计算机分配的资源，并拷贝父进程的数据。</li>
<li>子进程与父进程：我们编写的一段程序运行时就是一个进程，当我们在这段代码中调用特定函数新创建一个进程时，新创建的进程就是当前进程的子进程，而对于新创建的进程来说，当前进程就是它的父进程，子进程通过拷贝等手段继承父进程在创建子进程之前的数据、属性等。</li>
<li>多线程：上面说到进程是计算机上执行的每个活动。在实际编程中，一个进程中会有很多任务需要做。从而引发思考：一个进程中的多个任务是否也可以并发的执行？因为有些任务之间是没有联系的，也就是说有些任务完全可以同时进行而没有依赖问题。答案就是线程。与多进程相同的是，多线程也是为了让计算机资源得到充分利用并且程序的执行效率也会得到提高，与多进程不同的是，多线程并没有拷贝这种需求，它实际上是把一个进程分成多个片段。</li>
<li>重入性：尽管多线程系统开销少，但是也难免有缺陷，那就是重入性问题，使用多线程编程需要保证被多线程多次执行的函数的可重入性，所谓重入性就是函数被多个线程多次调用皆能正常执行。见附录2，有几个保证函数可重入性的条件。</li>
<li>线程安全：使用多线程编程除了需要保证函数的可重入性还需要保证线程安全，另外，可重入的函数一定是 线程安全的，但是反之不成立。</li>
<li>共享内存：根据字面意思就很好理解，通过把不同的进程中的逻辑内存映射到同一块物理内存中，进而允许两个进程共享同一块逻辑内存空间。它是进程间通信的一种方式。共享内存本身并没有提供同步机制。</li>
</ul>
</li>
<li>
<p>相关函数：</p>
<ul>
<li>
<p>多进程相关：</p>
<ol>
<li>
<p><code>fork()</code>：</p>
<ul>
<li>
<p>原型：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">pid_t</span> fork(<span class="keyword">void</span>);</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>说明：</p>
<p>通过复制调用者来创建新进程。这个新的进程简称为子进程。调用该函数的进程称为父进程。</p>
<p>子进程和父进程运行在不同的内存空间中。在调用该函数的时候，两个进程内存空间都拥有相同的内容。其中一个进程执行的内存写入，文件映射和解除映射操作不会影响到另一个进程。该函数的返回值在父子进程中不同，在父进程中返回子进程PID，在子进程中返回0。</p>
</li>
</ul>
</li>
<li>
<p><code>wait()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/wait.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">pid_t</span> wait(<span class="keyword">int</span> *stat_loc);</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<p>当调用这个函数的时候，当前进程会阻塞等待，该进程的某个子进程运行结束为止。
该结束的子进程的返回状态被存储在wait()函数的参数stat_loc变量中。</p>
</li>
</ul>
</li>
<li>
<p><code>system();</code></p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">system</span><span class="params">(<span class="keyword">char</span> *command)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<p>创建新的进程，执行制定命令。</p>
</li>
</ul>
</li>
<li>
<p>exec函数族：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">execl</span><span class="params">(cONst <span class="keyword">char</span> *path, <span class="keyword">const</span> <span class="keyword">char</span> *arg, ...)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">execlp</span><span class="params">(<span class="keyword">const</span> <span class="keyword">char</span> *file, <span class="keyword">const</span> <span class="keyword">char</span> *arg, ...)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">execle</span><span class="params">(<span class="keyword">const</span> <span class="keyword">char</span> *path, <span class="keyword">const</span> <span class="keyword">char</span> *arg, ..., <span class="keyword">char</span> *<span class="keyword">const</span> envp[])</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">execv</span><span class="params">(<span class="keyword">const</span> <span class="keyword">char</span> *path, <span class="keyword">char</span> *<span class="keyword">const</span> argv[])</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">execvp</span><span class="params">(<span class="keyword">const</span> <span class="keyword">char</span> *file, <span class="keyword">char</span> *<span class="keyword">const</span> argv[])</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">execve</span><span class="params">(<span class="keyword">const</span> <span class="keyword">char</span> *filename, <span class="keyword">char</span> *<span class="keyword">const</span> argv[], <span class="keyword">char</span> *<span class="keyword">const</span> envp[])</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<p>exec 函数族
execve 函数是该族的基础函数，其他函数是由该函数封装而来
exec 族被用启动新的指定路径下的程序来替换当前的程序。
函数名称后面的后缀不同参数不尽相同见下面附录1。</p>
</li>
</ul>
</li>
<li>
<p><code>exit()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">exit</span><span class="params">(<span class="keyword">int</span> status)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<p>终止进程并返回状态码。</p>
</li>
</ul>
</li>
</ol>
</li>
<li>
<p>多线程相关：</p>
<ol>
<li>
<p><code>pthread_create()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_create</span><span class="params">(<span class="keyword">pthread_t</span> *thread, <span class="keyword">const</span> <span class="keyword">pthread_attr_t</span> *attr,<span class="keyword">void</span> *(*start_routine) (<span class="keyword">void</span> *), <span class="keyword">void</span> *arg)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<ul>
<li>作用：创建线程</li>
<li>该函数开始一个新的线程在调用该函数的进程中。新开始的线程通过调用<code>start_routine()</code>函数指针指向的函数来执行，arg参数是该函数指针指向的函数唯一的参数。</li>
<li>该线程可以通过一下方式中的一个终止：
<ul>
<li>调用<code>pthread_exit()</code>函数，并确定退出状态值，该值可用于该进程中的调用<code>phread_join()</code>的其他线程。</li>
<li>该线程执行的函数退出，这相当于调用<code>phread_exit()</code>并带有返回值。</li>
<li>被取消（见<code>pthread_cancel()</code>）</li>
<li>调用<code>exit()</code>函数，或者在主函数中执行<code>return</code>。这会导致该进程中所有线程终止。</li>
</ul>
</li>
<li>attr参数指向一个pthread_attr_t类型的结构体，这个参数被用来在线程创建之初确定该线程的属性。</li>
<li>如果调用该函数成功创建了一个线程，那么该线程的ID会存储在thread参数中。这个标志会在其他的函数中用到。</li>
</ul>
</li>
</ul>
</li>
<li>
<p><code>pthread_join()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_join</span><span class="params">(<span class="keyword">pthread_t</span> thread, <span class="keyword">void</span> **retval)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<ul>
<li>该函数会等待由thread参数标志的线程终止。如果这个线程已经终止了，那么该函数立即返回。由thread参数标志的线程必须是可连接的。</li>
<li>如果retval参数不为空，那么该函数会拷贝目标线程的目标线程的退出状态（目标线程提供返回状态值给pthread_exit();）到该参数中。如果目标线程已经被取消了，那么该参数会存储PTHREAD_CANCELED。</li>
</ul>
</li>
</ul>
</li>
<li>
<p><code>pthread_detach()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_detach</span><span class="params">(<span class="keyword">pthread_t</span> thread)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<p>该函数会把由thread参数指向的线程标记为分离。一个被标记分离的线程终止后，该线程的资源会被系统自动收回，不需要其他线程进程其他的操作。尝试标记已经分离的线程是不明操作，会导致未知错误。</p>
</li>
</ul>
</li>
<li>
<p><code>pthread_self()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="keyword">pthread_t</span> pthread_self(<span class="keyword">void</span>);</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<ul>
<li>该函数会返回调用者的PID，该值与调用<code>thread_create()</code>函数返回的thread值相同。</li>
</ul>
</li>
</ul>
</li>
<li>
<p><code>pthread_equal</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_equal</span><span class="params">(<span class="keyword">pthread_t</span> t1, <span class="keyword">pthread_t</span> t2)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<ul>
<li>该函数比较两个线程的标记t1和t2是否指向同一个线程。</li>
<li>如果两个标记指向同一个线程会返回一个非零数，反之返回０。</li>
</ul>
</li>
</ul>
</li>
<li>
<p><code>pthread_exit()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">pthread_exit</span><span class="params">(<span class="keyword">void</span> *retval)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
</li>
<li>
<p>该函数会终止调用该函数的线程，并通过参数retval返回一个值，该值可用于同一进程中的其他线程调用<code>pthread_join()</code>。</p>
</li>
</ul>
</li>
<li>
<p>线程同步机制：</p>
<ol>
<li>
<p>互斥：</p>
<ol>
<li>
<p><code>pthread_mutex_init()</code>、<code>pthread_mutex_destroy()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_mutex_init</span><span class="params">(<span class="keyword">pthread_mutex_t</span> *<span class="keyword">restrict</span> mutex,<span class="keyword">const</span> <span class="keyword">pthread_mutexattr_t</span> *<span class="keyword">restrict</span> attr)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_mutex_destroy</span><span class="params">(<span class="keyword">pthread_mutex_t</span> *mutex)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<ul>
<li><code>pthread_mutex_destroy()</code>:
<ul>
<li>该函数销毁参数mutex引用的的互斥对象，实际上，该互斥对象会变成未初始化的状态。</li>
<li>一个被销毁的互斥锁可以使用<code>pthread_mutex_init()</code>重新初始化。在互斥锁被销毁后引用该互斥锁会导致未定的引用的错误。</li>
<li>销毁一个未上锁的初始化互斥对象是安全的。当尝试销毁一个通过其他线程使用的锁定的互斥锁或一个已经被禁用的互斥锁会导致未定义行为的错误。</li>
</ul>
</li>
<li><code>pthread_mutex_init()</code>：
<ul>
<li>该函数会初始化一个被参数mutex引用的互斥锁，该互斥锁的属性在参数attr中规定。</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>
<p><code>pthread_mutex_lock()</code>、<code>pthread_mutex_trylock()</code>和<code>pthread_mutex_unlock</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_mutex_lock</span><span class="params">(<span class="keyword">pthread_mutex_t</span> *mutex)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_mutex_trylock</span><span class="params">(<span class="keyword">pthread_mutex_t</span> *mutex)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_mutex_unlock</span><span class="params">(<span class="keyword">pthread_mutex_t</span> *mutex)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<ul>
<li><code>pthread_mutex_lock()</code>
<ul>
<li>该函数会把参数mutex引用的互斥锁上锁返回０或者EOWNERDEAD，如果该互斥锁已经被其他线程上锁了，那么该线程会阻塞，直到该互斥锁可用。</li>
</ul>
</li>
<li><code>pthread_mutex_trylock()</code>
<ul>
<li>pthread_mutex_trylock()函数等效于pthread_mutex_lock()，除非mutex引用的互斥对象当前被锁定（由任何线程，包括当前线程），则调用应立即返回。</li>
</ul>
</li>
<li><code>pthread_mutex_unlock()</code>
<ul>
<li>pthread_mutex_unlock()函数将释放互斥锁引用的互斥锁对象。 释放互斥锁的方式取决于互斥锁的类型属性。</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ol>
</li>
<li>
<p>读写锁：</p>
<ol>
<li>
<p>``pthread_rwlock_init()<code>、</code>pthread_rwlock_destory()`：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_rwlock_destroy</span><span class="params">(<span class="keyword">pthread_rwlock_t</span> *rwlock)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_rwlock_init</span><span class="params">(<span class="keyword">pthread_rwlock_t</span> *<span class="keyword">restrict</span> rwlock,<span class="keyword">const</span> <span class="keyword">pthread_rwlockattr_t</span> *<span class="keyword">restrict</span> attr)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">pthread_rwlock_t</span> rwlock = PTHREAD_RWLOCK_INITIALIZER;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<ul>
<li>``pthread_rwlock_init()`函数会分配参数rwkock参数引用的读写所所需的所有资源，并将读写锁初始化为具有参数attr指定的属性，并置为解锁状态，如果attr为NULL，则应使用默认的读写锁属性; 效果与传递默认读写锁属性对象的地址相同。</li>
<li><code>pthread_rwlock_destory()</code>函数将销毁rwlock引用的读写锁对象，并释放锁使用的所有资源。</li>
</ul>
</li>
</ul>
</li>
<li>
<p><code>pthread_rwlock_rdlock()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_rwlock_tryrdlock</span><span class="params">(<span class="keyword">pthread_rwlock_t</span> *rwlock)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_rwlock_rdlock</span><span class="params">(<span class="keyword">pthread_rwlock_t</span> *rwlock)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<p>两个函数函数都会对由rwlock引用的读写锁解开读锁。但是对于<code>pthread_rwlock_rdlock()</code>函数如果写入权限没有上锁并且互斥锁上没有写入权限被阻塞，则调用线程获取读锁定。调用该函数的线程读权限会被上锁。try函数遇到这种情况会返回调用失败两个函数都是成功返回０。</p>
</li>
</ul>
</li>
<li>
<p><code>pthread_rwlock_wrlock()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_rwlock_trywrlock</span><span class="params">(<span class="keyword">pthread_rwlock_t</span> *rwlock)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_rwlock_wrlock</span><span class="params">(<span class="keyword">pthread_rwlock_t</span> *rwlock)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<p>两个函数同样都会为调用者加写权限锁，但是try函数回去尝试，也就是说如果任何线程当前持有rwlock（用于读或写），函数将调用失败。但是另一个函数遇到这种情况会阻塞。函数执行成功返回０。</p>
</li>
</ul>
</li>
<li>
<p><code>pthread_rwlock_unlock()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;pthread.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_rwlock_unlock</span><span class="params">(<span class="keyword">pthread_rwlock_t</span> *rwlock)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<p>该函数将释放由rwlock引用的读写锁对象上的锁。 如果读写锁定rwlock未被调用线程保持，则结果是不确定的。</p>
</li>
</ul>
</li>
</ol>
</li>
<li>
<p>条件变量：</p>
<ol>
<li>
<p><code>thread_cond_init()</code>、<code>thread_cond_destory()</code></p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_cond_destroy</span><span class="params">(<span class="keyword">pthread_cond_t</span> *cond)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_cond_init</span><span class="params">(<span class="keyword">pthread_cond_t</span> *<span class="keyword">restrict</span> cond,<span class="keyword">const</span> <span class="keyword">pthread_condattr_t</span> *<span class="keyword">restrict</span> attr)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">pthread_cond_t</span> cond = PTHREAD_COND_INITIALIZER;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<p><code>pthread_cond_destroy()</code>函数将销毁由cond指定的给定条件变量; 实际上，对象会处于未初始化状态。可以使用<code>pthread_cond_init()</code>重新初始化已销毁的条件变量对象; 在对象被销毁之后引用该对象的结果是未定义的。<code>pthread_cond_init()</code>函数应使用attr引用的属性初始化cond引用的条件变量。</p>
</li>
</ul>
</li>
<li>
<p><code>thread_cond_wait()</code>、<code>thread_cond_timedwait()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_cond_timedwait</span><span class="params">(<span class="keyword">pthread_cond_t</span> *<span class="keyword">restrict</span> cond, <span class="keyword">pthread_mutex_t</span> *<span class="keyword">restrict</span> mutex, <span class="keyword">const</span> struct timespec *<span class="keyword">restrict</span> abstime)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_cond_wait</span><span class="params">(<span class="keyword">pthread_cond_t</span> *<span class="keyword">restrict</span> cond, <span class="keyword">pthread_mutex_t</span> *<span class="keyword">restrict</span> mutex)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<p>两个函数都会阻塞条件变量。 应用程序应确保在调用线程锁定互斥锁的情况下调用这些函数; 否则，会产生错误或未定义的行为（对于其他互斥锁）。</p>
</li>
</ul>
</li>
<li>
<p><code>thread_cond_signal()</code>、<code>thread_cond_broadcast()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;pthread.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_cond_broadcast</span><span class="params">(<span class="keyword">pthread_cond_t</span> *cond)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">pthread_cond_signal</span><span class="params">(<span class="keyword">pthread_cond_t</span> *cond)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<p><code>pthread_cond_broadcast()</code>函数将取消阻止当前在指定条件变量cond上阻塞的所有线程。<code>pthread_cond_signal()</code>函数应解除阻塞在指定条件变量cond上阻塞的至少一个线程（如果在cond上阻塞了任何线程）。</p>
</li>
</ul>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
<li>
<p>共享内存相关：</p>
<ol>
<li>
<p><code>shmget()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/ipc.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/shm.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">shmget</span><span class="params">(<span class="keyword">key_t</span> key, <span class="keyword">size_t</span> size, <span class="keyword">int</span> shmflg)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<ul>
<li>
<p>该函数返回与参数key相关联的共享内存片段的标识符（identifier）。</p>
</li>
<li>
<p>该函数可以用于获取先前创建的共享内存的idenfifier（当shmflg为0并且key值不是IPC_PRIVATE&lt; 预定义宏，见附录3 &gt;的时候）</p>
</li>
<li>
<p>该函数还可以用于创建一个新共享内存，新的共享内存大小为size参数向上取整到PAGE_SIZE(预定义宏，见附录3)。使用该函数创建新的共享内存需满足如下条件：</p>
</li>
<li>
<ol>
<li>key没有与它相对应的共享内存(无论参数key的值是不是IPC_PRIVATE（预定义宏，见附录3）)</li>
</ol>
</li>
<li>
<ol start="2">
<li>shmflg参数指定了IPC_CREAT（预定义宏，见附录3）</li>
</ol>
</li>
<li>
<p>如果参数shmflg指定了IPC_CREAT和IPC_EXECL并且key 已经存在与其相关联的共享内存，那么shmget函数创建新的共享内存失败，并且erron会被设置为EEXIST。(这有点像O_CREAT | O_EXCL 组合对于open()函数带来的影响)</p>
</li>
<li>
<p>shmflg参数的取值如下：</p>
</li>
<li>
<p>IPC_CREAT IPC_EXCL、SHM_HUGETLB、SHM_HUGE2MB(SHM_HUGE_1GB)、SHM_NORESERVE（详情见附录3）</p>
</li>
</ul>
</li>
</ul>
</li>
<li>
<p><code>shmat()</code>、<code>shmdt()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/shm.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> *<span class="title">shmat</span><span class="params">(<span class="keyword">int</span> shmid, <span class="keyword">const</span> <span class="keyword">void</span> *shmaddr, <span class="keyword">int</span> shmflg)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">shmdt</span><span class="params">(<span class="keyword">const</span> <span class="keyword">void</span> *shmaddr)</span></span>;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>函数说明：</p>
<ul>
<li>shmat();</li>
<li>该函数把通过shmid标志的共享内存段链接到调用该函数的进程所在的地址空间中。</li>
<li>这个被链接的地址空间由shmaddr参数的如下定义所规定：
<ol>
<li>如果shmaddr参数为空，系统会选择一个合适的（未使用的）对齐页地址去链接共享内存。</li>
<li>如果shmaddr参数不为空并且shmflg参数指定了SHMLBA(见附录3)，会链接到shmaddr参数向下取整到离SHMLBA倍数最近值的地址。</li>
<li>除此之外，一定会链接到shmaddr 附近的对齐页地址。</li>
</ol>
</li>
<li>除了SHM_RND以外，shmflg位掩码参数还可能使用到一下规定的标志：</li>
<li>SHM_EXEC、SHM_RDONLY、SHM_REMAP（详细说明见附录3）</li>
<li>shmdt();</li>
<li>与上面的函数相反，该函数通过shmid表示的共享内存段从调用该用书的进程所在的地址空间中断开。</li>
<li>这个被断开的共享内存段必须是目前链接的，并且shmaddr参数的值为调用shmat()函数的返回值。</li>
<li>如果shmdt()调用成功，系统会更新与共享内存相关联的shmid_ds结构体，该结构体成员如下：</li>
<li>shm_ttime : 被设置为当前时间。</li>
<li>shm_lpid : 被设置为被调用的进程的进程ID。</li>
<li>shm_nattch ：这个值逐一递减，如果这个值减为0并且这个共享内存段被标记为删除，那么这个共享内存段就被删除了。</li>
</ul>
</li>
</ul>
</li>
<li>
<p><code>shmctl()</code>：</p>
<ul>
<li>
<p>函数原型及头文件：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/ipc.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;sys/shm.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">shmctl</span><span class="params">(<span class="keyword">int</span> shmid, <span class="keyword">int</span> cmd, struct shmid_ds *buf)</span></span>;</span><br></pre></td></tr></table></figure></p>
<ul>
<li>
<p>该函数执行由cmd参数指定的操作，cmd参数存储在由shmid参数存储的识别码指向的共享内存段。</p>
</li>
<li>
<p>buf参数是一个shmid_ds结构体指针，shmid_ds结构体在头文件&lt;sys/shm.h&gt;中定义，如下所示：</p>
<p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">shmid_ds</span> &#123;</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">ipc_perm</span> <span class="title">shm_perm</span>;</span>	<span class="comment">/* 所有权和权限 */</span></span><br><span class="line">    <span class="keyword">size_t</span> shm_segsz;			<span class="comment">/* 段大小（单位：字节） */</span></span><br><span class="line">    <span class="keyword">time_t</span> shm_atime;			<span class="comment">/* 最后的链接时间 */</span></span><br><span class="line">    <span class="keyword">time_t</span> shm_dtime;			<span class="comment">/* 最后的断开链接时间 */</span></span><br><span class="line">    <span class="keyword">time_t</span> shm_ctime;			<span class="comment">/* 最后的更改时间 */</span></span><br><span class="line">    <span class="keyword">pid_t</span>  shm_cpid;			<span class="comment">/* 创建者的PID */</span></span><br><span class="line">    <span class="keyword">pid_t</span>  shm_lpid;			<span class="comment">/* 最后的shmat()函数或shmdt()函数的pid */</span></span><br><span class="line">    ...</span><br><span class="line">&#125;;</span><br><span class="line">ipc_perm结构体的定义如下（其中udi、gid和mode可设置为IPC_SET）：</span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ipc_perm</span> &#123;</span></span><br><span class="line">	<span class="keyword">key_t</span>			__key;		<span class="comment">/* 提供给shmget()函数的键值 */</span></span><br><span class="line">	<span class="keyword">uid_t</span>			uid;		<span class="comment">/* 有效的拥有者的UID */</span></span><br><span class="line">	<span class="keyword">gid_t</span>			gid;		<span class="comment">/* 有效的拥有者的GID */</span></span><br><span class="line">	<span class="keyword">uid_t</span>			cuid;		<span class="comment">/* 有效的创建者UID */</span></span><br><span class="line">	<span class="keyword">gid_t</span> 			cgid;		<span class="comment">/* 有效的创建者GID */</span></span><br><span class="line">	<span class="keyword">unsigned</span> <span class="keyword">short</span>	mode;		<span class="comment">/* 权限 + SHM_DEST 和 SHM_LOCKED 标记 */</span></span><br><span class="line">	<span class="keyword">unsigned</span> <span class="keyword">short</span>	__seq;		<span class="comment">/* 序列号 */</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
</li>
<li>
<p>cmd参数的有效值如下：</p>
<p>IPC_STAT、IPC_SET IPC_RMID、IPC_INFO、SHM_INFO、SHM_STAT、SHM_LOCK、SHM_UNLOCK 。</p>
</li>
</ul>
</li>
</ul>
</li>
</ol>
</li>
</ul>
</li>
</ol>
<hr>
<ul>
<li>
<p>附录1（摘自网络）：</p>
<table>
<thead>
<tr>
<th>后缀</th>
<th>参数</th>
</tr>
</thead>
<tbody>
<tr>
<td>l</td>
<td>接收以逗号为分隔的参数列表，以NULL为结束符</td>
</tr>
<tr>
<td>v</td>
<td>接收以NULL为结束的字符串数组</td>
</tr>
<tr>
<td>p</td>
<td>接收以NULL为结束的字符串数组指针，并可以利用DOS的PATH变量查找子程序文件</td>
</tr>
<tr>
<td>e</td>
<td>传递环境变量。</td>
</tr>
</tbody>
</table>
</li>
<li>
<p>附录2（摘自网络）：</p>
<ol>
<li>不在函数内部使用静态或全局数据。</li>
<li>不返回静态或全局数据，所有数据都由函数的调用者提供。</li>
<li>使用本地数据，或通过拷贝全局数据到本地来保护全局数据。</li>
<li>不调用不可重入性函数。</li>
</ol>
</li>
<li>
<p>附录三（翻译自man手册）：</p>
<table>
<thead>
<tr>
<th>宏名称</th>
<th>意义</th>
</tr>
</thead>
<tbody>
<tr>
<td>IPC_CREAT</td>
<td>创建一个新的段，如果这个标志没有被使用，shmget()函数将会寻找与这个段相对应的key参数值，并且检查使用者是否有读取这个段的权限。</td>
</tr>
<tr>
<td>IPC_EXCL</td>
<td>该标志与IPC_BREAT一起被用作确认本次创建共享内存的调用成功与否。</td>
</tr>
<tr>
<td>IPC_PRIVATE</td>
<td>它不是一个标志字段，而是一个key_t类型的值，如果函数调用的时候key参数中存储这个特殊的值，系统调用会忽略除了shmflg中最不重要的9位意外的所有并且创建一个新的共享内存。</td>
</tr>
<tr>
<td>IPC_STAT</td>
<td>从内核中拷贝shmid中由buf指向的shmid_ds结构相关的数据结构信息。对于共享内存段调用者必须拥有可读权限。</td>
</tr>
<tr>
<td>IPC_SET</td>
<td>往参数buf指针指向的shmid_ds结构体的某些成员写入与该共享内存段相关联的内核数据结构，并且更新该结构体中的shm_ctime成员。以下成员可能会被改变：shm_perm.uid、shm_perm.gid和（最不重要的九位）shm_perm.mode。调用进程的有效UID必须与拥有者（shm_perm.uid）或共享内存的创建者（shm_per.cuid）相匹配，或者与一定是拥有特权的调用者相匹配。</td>
</tr>
<tr>
<td>IPC_RMID</td>
<td>标记被销毁的共享内存段，实际上，这个共享内存段实在进程销毁的时候被销毁。（当shmid_ds相关构成员shm_nattch为空的时候）。调用者必须是共享内存的拥有者或者创建者，或者拥有特权。buf参数被忽略。</td>
</tr>
<tr>
<td>SHM_NORESREVE</td>
<td>（从linux内核2.6.15以后）这个标志与mmap()函数的MAP_NORESERVE 标志具有同样的目的。不保留交换空间对于共享内存段，当交换空间被保留了，他会保证共享内存是可用的。当交换空间没有被保留，并且物理内存不可用，那么可能会在写入时获取SIGSEGV。也可以查阅<code>/proc/sys/vm/overcommit</code>文件。</td>
</tr>
<tr>
<td>SHM_REMAP</td>
<td>（LInux特有）这个标志指定了在共享内存段中从shmaddr参数开始到段最后的范围内的段映射应该被替换成现有的映射。（一般情况下，一个EINVAL错误可能是由于一个映射在地址范围内已经存在）在这个案例中，shmaddr参数必须不为空。</td>
</tr>
<tr>
<td>SHM_RDONLY</td>
<td>以只读的方式链接共享内存段。进程对共享内存段必须有读取权限。如果标志没有被指定，那么共享内存段会被以可读可写方式链接，并且进程对于该共享内存段必须拥有可读和可写权限。但这不意味着对共享内存段有只写权限。</td>
</tr>
<tr>
<td>SHM_EXEC</td>
<td>（Linux特有，从linux2.6.9以后）允许执行共享内存段中的内容。调用者对于共享内存段必须拥有可执行权限。</td>
</tr>
<tr>
<td>SHM_HUGETLB</td>
<td>（从linux内核2.6版以后）为共享内存段分配巨大空间，详情见linux内核源码文件中<code>Documentation/vm/hugetlbpage.txt</code>获取更多信息。</td>
</tr>
<tr>
<td>SHM_HUGE2MB,SHM_HUGE1GB</td>
<td>（从linux内核3.8之后）与SHM_HUGETLB一起被用作选择替代hugetlb大页面的大小（分别是2MB和1GB），并且支持超过hugetlb大页面的大小。</td>
</tr>
</tbody>
</table>
</li>
<li>
<p>参考资料：</p>
<blockquote>
<p>参考网站：<a href="https://blog.csdn.net/hello_bravo_/article/details/52497401" target="_blank" rel="noopener">多进程编程总结</a>、<a href="https://www.xuebuyuan.com/943688.html" target="_blank" rel="noopener">C语言多进程编程</a>、<a href="https://www.cnblogs.com/alanfeng/p/5055141.html" target="_blank" rel="noopener">多线程和多进程的区别（小结）</a>、<a href="https://baike.baidu.com/item/%E7%A8%8B%E5%BA%8F%E5%B9%B6%E5%8F%91%E6%89%A7%E8%A1%8C/7387706" target="_blank" rel="noopener">百度百科：程序并发执行</a>、<a href="https://blog.csdn.net/aile770339804/article/details/7443921" target="_blank" rel="noopener">linux下c语言编程exec函数使用</a></p>
<p>参考书籍：<a href="http://product.dangdang.com/25154067.html" target="_blank" rel="noopener">C语言核心技术</a> 、man手册</p>
</blockquote>
</li>
</ul>
	
	</div>
	
	<div id="current-post-cover" data-scr="https://w.wallhaven.cc/full/ym/wallhaven-ym233x.jpg"></div>

	<!-- relate post, comment...-->
	<div class="investment-container">
		<div class="investment-header">
			<div class="investment-title-1">
				<div class="on">相关文章</div>
				<div>评论</div>
				<div>分享</div>
			</div>
			<div class="investment-title-2">	            
				
	<span>
		<a href="javascript: window.scrollTo(0, 0);">返回顶部</a>
		
			<a href="/2019/09/02/用户信息获取/" title="用户信息获取" rel="prev">
				&laquo;上一篇
			</a>
		
		
			<a href="/2019/09/02/Linux常见配置文件/" title="Linux常见配置文件" rel="next">
				下一篇&raquo;
			</a>
			
	</span>


      		
			</div>	
		</div>
		
		<div class="investment-content">
			<div class="investment-content-list">
				

<div class="relate-post">
	
		<ul>
			
					<li>
						<div class="relate-post-text">
							<a class="relate-post-title" href="/2019/09/27/八大排序算法总结/" title="八大排序算法总结">
								八大排序算法总结			
							</a>
							<p class="relate-post-date">
								<i class="fa fa-calendar"></i>
								九月 27日, 2019				
							</p>
							<p class="relate-post-content">
								直接插入排序算法


概述
直接插入排序算法在逻辑上将整体数据分为两部分，一部分是已排序部分，另一部分是待排序部分 。
排序的过程是：在待排序部分逐步的拿出一个元素，将其插入到已排序部分中合理的位置 。


适用场景
插入排序在对几乎...
							</p>
						</div>

						<div class="relate-post-cover">
							<a href="/2019/09/27/八大排序算法总结/" title="八大排序算法总结">				
								
								<img class="lazy" src="/img/placeholder.jpg" data-src="https://w.wallhaven.cc/full/ox/wallhaven-oxj7mm.jpg" alt="八大排序算法总结"/>
							</a>
						</div>
					</li>											
			
			
					<li>
						<div class="relate-post-text">
							<a class="relate-post-title" href="/2019/09/16/hexo低成本搭建静态网页博客/" title="hexo低成本搭建静态网页博客">
								hexo低成本搭建静态网页博客			
							</a>
							<p class="relate-post-date">
								<i class="fa fa-calendar"></i>
								九月 16日, 2019				
							</p>
							<p class="relate-post-content">
								引言
好多同学有写博客的习惯，也有各大例如csd*、简*等博客平台。
但是这些平台毕竟是盈利平台，无法做到对自己的博客完全掌控，有一丝丝的不爽快。想要DIY一下几乎不可能。在这里推荐同学们自己动手丰衣足食。
准备知识

github最...
							</p>
						</div>

						<div class="relate-post-cover">
							<a href="/2019/09/16/hexo低成本搭建静态网页博客/" title="hexo低成本搭建静态网页博客">				
								
								<img class="lazy" src="/img/placeholder.jpg" data-src="https://w.wallhaven.cc/full/45/wallhaven-45yd68.jpg" alt="hexo低成本搭建静态网页博客"/>
							</a>
						</div>
					</li>											
			
			
					<li>
						<div class="relate-post-text">
							<a class="relate-post-title" href="/2019/09/02/Linux常见配置文件/" title="Linux常见配置文件">
								Linux常见配置文件			
							</a>
							<p class="relate-post-date">
								<i class="fa fa-calendar"></i>
								九月 2日, 2019				
							</p>
							<p class="relate-post-content">
								
转载自CoderZhuang，对CoderZhuang先生的博客进行补充和整理。


/etc 配置文件

/etc/passwd 用户数据库，其中的域给出了用户名、真实姓名、家目录、加密口令和用户的其他信息

/etc/group...
							</p>
						</div>

						<div class="relate-post-cover">
							<a href="/2019/09/02/Linux常见配置文件/" title="Linux常见配置文件">				
								
								<img class="lazy" src="/img/placeholder.jpg" data-src="https://w.wallhaven.cc/full/2e/wallhaven-2eod59.jpg" alt="Linux常见配置文件"/>
							</a>
						</div>
					</li>											
			
			
					<li>
						<div class="relate-post-text">
							<a class="relate-post-title" href="/2019/09/02/deepin系统使用笔记/" title="deepin系统使用笔记">
								deepin系统使用笔记			
							</a>
							<p class="relate-post-date">
								<i class="fa fa-calendar"></i>
								九月 2日, 2019				
							</p>
							<p class="relate-post-content">
								

如果你是小白用户并且没有人在旁边指导，那么建议不要自行更改本文给出的命令。
图形界面相关的东西自行探索。


deepin系统安装后推荐配置
sudo apt-get install -y git wget curl openss...
							</p>
						</div>

						<div class="relate-post-cover">
							<a href="/2019/09/02/deepin系统使用笔记/" title="deepin系统使用笔记">				
								
								<img class="lazy" src="/img/placeholder.jpg" data-src="https://w.wallhaven.cc/full/j5/wallhaven-j5yerq.jpg" alt="deepin系统使用笔记"/>
							</a>
						</div>
					</li>											
			
			
					<li>
						<div class="relate-post-text">
							<a class="relate-post-title" href="/2019/09/02/Linux三剑客之awk的使用/" title="Linux三剑客之awk的使用">
								Linux三剑客之awk的使用			
							</a>
							<p class="relate-post-date">
								<i class="fa fa-calendar"></i>
								九月 2日, 2019				
							</p>
							<p class="relate-post-content">
								
awk 是一款极其强大的文本处理工具，其语言于c语言的语法极其相似，上手很容易
内置变量与运算符数据来自RUNOOB



简单用法
12awk [参数] 'awk代码'awk [参数] -f awk脚本文件


常用参数
1234...
							</p>
						</div>

						<div class="relate-post-cover">
							<a href="/2019/09/02/Linux三剑客之awk的使用/" title="Linux三剑客之awk的使用">				
								
								<img class="lazy" src="/img/placeholder.jpg" data-src="https://w.wallhaven.cc/full/g8/wallhaven-g8md6l.jpg" alt="Linux三剑客之awk的使用"/>
							</a>
						</div>
					</li>											
			
			
					<li>
						<div class="relate-post-text">
							<a class="relate-post-title" href="/2019/09/02/linux三剑客之grep的使用/" title="linux三剑客之grep的使用">
								linux三剑客之grep的使用			
							</a>
							<p class="relate-post-date">
								<i class="fa fa-calendar"></i>
								九月 2日, 2019				
							</p>
							<p class="relate-post-content">
								
部分内容源自网络和grep帮助信息。

用法
1grep [参数选项] [模式串] [文件或目录]
常用参数选项说明


-o只显示与模式串匹配的内容。


-E 使用扩展正则表达式。
栗子：
1cat index.html | g...
							</p>
						</div>

						<div class="relate-post-cover">
							<a href="/2019/09/02/linux三剑客之grep的使用/" title="linux三剑客之grep的使用">				
								
								<img class="lazy" src="/img/placeholder.jpg" data-src="https://w.wallhaven.cc/full/39/wallhaven-392lk9.jpg" alt="linux三剑客之grep的使用"/>
							</a>
						</div>
					</li>											
			
			
					<li>
						<div class="relate-post-text">
							<a class="relate-post-title" href="/2019/09/02/MYSQL-笔记1/" title="MYSQL-笔记1">
								MYSQL-笔记1			
							</a>
							<p class="relate-post-date">
								<i class="fa fa-calendar"></i>
								九月 2日, 2019				
							</p>
							<p class="relate-post-content">
								
在MYSQL中查询操作涉及内容

[TOC]
function

对待查询字段在待查找表中出现的若干记录中的函数参数中指定的字段进行某些操作。


COUNT ： 统计
SUM ： 求和
AVG ： 平均数

more about ...
							</p>
						</div>

						<div class="relate-post-cover">
							<a href="/2019/09/02/MYSQL-笔记1/" title="MYSQL-笔记1">				
								
								<img class="lazy" src="/img/placeholder.jpg" data-src="https://w.wallhaven.cc/full/6k/wallhaven-6kyk9w.jpg" alt="MYSQL-笔记1"/>
							</a>
						</div>
					</li>											
			
			
					<li>
						<div class="relate-post-text">
							<a class="relate-post-title" href="/2019/09/02/HDU-1276/" title="HDU-1276">
								HDU-1276			
							</a>
							<p class="relate-post-date">
								<i class="fa fa-calendar"></i>
								九月 2日, 2019				
							</p>
							<p class="relate-post-content">
								

题目描述
某部队进行新兵队列训练，将新兵从一开始按顺序依次编号，并排成一行横队，训练的规则如下：从头开始一至二报数，凡报到二的出列，剩下的向小序号方向靠拢，再从头开始进行一至三报数，凡报到三的出列，剩下的向小序号方向靠拢，继续从头...
							</p>
						</div>

						<div class="relate-post-cover">
							<a href="/2019/09/02/HDU-1276/" title="HDU-1276">				
								
								<img class="lazy" src="/img/placeholder.jpg" data-src="https://w.wallhaven.cc/full/ym/wallhaven-ym28eg.jpg" alt="HDU-1276"/>
							</a>
						</div>
					</li>											
			
			
					<li>
						<div class="relate-post-text">
							<a class="relate-post-title" href="/2019/09/02/CPU信息获取/" title="CPU信息获取">
								CPU信息获取			
							</a>
							<p class="relate-post-date">
								<i class="fa fa-calendar"></i>
								九月 2日, 2019				
							</p>
							<p class="relate-post-content">
								

准备知识


/proc文件系统是一个伪文件系统，该文件系统中存储着内核控制相关信息，通俗点说就是这个目录是虚拟的，它受内核直接控制，存储与内核控制相关的数据，与其他目录不同的是/proc目录不是真实存储在硬盘中的，它的数据存储在...
							</p>
						</div>

						<div class="relate-post-cover">
							<a href="/2019/09/02/CPU信息获取/" title="CPU信息获取">				
								
								<img class="lazy" src="/img/placeholder.jpg" data-src="https://w.wallhaven.cc/full/wy/wallhaven-wyd5jx.jpg" alt="CPU信息获取"/>
							</a>
						</div>
					</li>											
			
			
					<li>
						<div class="relate-post-text">
							<a class="relate-post-title" href="/2019/09/02/POJ-1979/" title="POJ-1979">
								POJ-1979			
							</a>
							<p class="relate-post-date">
								<i class="fa fa-calendar"></i>
								九月 2日, 2019				
							</p>
							<p class="relate-post-content">
								

原题目：
Description
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. ...
							</p>
						</div>

						<div class="relate-post-cover">
							<a href="/2019/09/02/POJ-1979/" title="POJ-1979">				
								
								<img class="lazy" src="/img/placeholder.jpg" data-src="https://w.wallhaven.cc/full/wy/wallhaven-wydj37.jpg" alt="POJ-1979"/>
							</a>
						</div>
					</li>											
			
			
		</ul>
	
</div>	
			</div>
			<div class="investment-content-list">
				<div class="layout-comment">

	

		

			<!-- I don't know !!!-->
			<div>Please check the comment setting in config.yml of hexo-theme-Annie!</div>
			
		
		
	

</div>
			</div>
			<div class="investment-content-list">
				<div class="layout-share">
	
	

		
			
			<!-- socialShare share -->
			<div class="social-share"></div>

<!--  css & js -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">
<script async src="https://cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>
			
		
		
	
</div>


			</div>
		</div>	
	</div>
	</div>
</div>



	<!-- leancloud -->
	<!--
	时间：2018-11-27
	描述：
		文章访问量：visitors
		文章喜欢量：likes	
		文章排行榜：topNPost
		其他得说明：
			01-Cookie相关的函数 
				https://blog.csdn.net/somehow1002/article/details/78511541（Author：somehow1002）
			02-visitors相关的函数 
				https://blog.csdn.net/u013553529/article/details/63357382（Author：爱博客大伯）
				https://notes.doublemine.me/2015-10-21-为NexT主题添加文章阅读量统计功能.html（Author：夏末）
			03-topNPost相关的函数
				https://hoxis.github.io/hexo-next-read-rank.html（Author：hoxis）
			04-likes相关的函数，
				参考了01 & 02进行简单的设计与实现
-->


	


<!-- show math formula -->



	 
	<script src="/plugin/clipboard/clipboard.js"></script>
	<script>
		// Copy code !
	    function codePreprocessing() {
	        $("#article-content .highlight").each(function() {

	            $(this).wrap('<div id="post-code"></div>');

	        })

	        $("#article-content #post-code").each(function() {

	            $(this).prepend('<nav class="copy-nav"><span><i class="code-language"></i></span></nav>');

	        })

	        $("#article-content .copy-nav").each(function() {
	            var temp = $(this).next().attr('class'),
	                language = ((temp.length > 9) && (temp != null)) ? temp.substr(10) : "none"; //why 9? Need to check language?

	            $(this).find('.code-language').text(language);

	            $(this).append('<span class="copy-btn"><i class="fa fa-copy" aria-hidden="true"></i></span>');

	        });
	    }

		function codeCopy() {
		    $('#article-content #post-code').each(function(i) {
		        var codeCopyId = 'codeCopy-' + i;

		        var codeNode = $(this).find('.code'),
		            copyButton = $(this).find('.copy-btn');

		        codeNode.attr('id', codeCopyId);
		        copyButton.attr('data-clipboard-target-id', codeCopyId);
		    })

		    
			var clipboard = new ClipboardJS('.copy-btn', {
					target: function(trigger) {
						return document.getElementById(trigger.getAttribute('data-clipboard-target-id'));
					}
		      	});

			//pure js
			function showTooltip(elem, msg) {		   
				elem.setAttribute('aria-label', msg);
				elem.setAttribute('class', 'copy-btn copy-status');
				setTimeout(function() {
					elem.setAttribute('class', 'copy-btn');
				}, 2000);
			}

			clipboard.on('success', function(e) {
			    e.clearSelection();
			    console.info('Action:', e.action);		   
			    console.info('Trigger:', e.trigger);
			    showTooltip(e.trigger, 'Copied!');
			    
			});
			clipboard.on('error', function(e) {
			    console.error('Action:', e.action);
			    console.error('Trigger:', e.trigger);
			});
		

		}

		if ($('.layout-post').length) {
		    codePreprocessing();
		    codeCopy();
		} 
	</script>





<link rel="stylesheet" href="/plugin/fancybox/jquery.fancybox.css">
<script src="/plugin/fancybox/jquery.fancybox.js"></script>

<script type="text/javascript">
	var titleID = $('.article-title a'),
		imageID = $('.article-content img'),
		videoID = $('.article-content video');

	var postTitle = titleID.text() ? titleID.text() : "No post title!";

	imageID.each(function() {
		var imgPath = $(this).attr('src'),
			imgTitle = $(this).attr('alt') ? $(this).attr('alt') : "No image description!";

		//给每个匹配的<img>元素打包, 即添加父元素<a>
		$(this).wrap('<a data-fancybox="gallery" data-caption=" 《 ' + postTitle + ' 》 ' + imgTitle + ' "  href=" ' + imgPath + ' "> </a>');
	});

	videoID.each(function() {
		var videoPath = $(this).attr('src');

		//给每个匹配的<img>元素打包, 即添加父元素<a>
		$(this).wrap('<a data-fancybox href=" ' + videoPath + ' "> </a>');
	});
	//TODO：支持html5 video

	if($('#layout-post').length) {
		$('[data-fancybox="gallery"]').fancybox({
			loop: true,
			buttons: [
				"zoom",
				"share",
				"slideShow",
				"fullScreen",
				//"download",
				"thumbs",
				"close"
			],
			protect: false
		});
	}
</script>
		</main>

		<!--footer-->
		<footer>
	<div class="social">
		<ul>
	
		<li>
			<a href="http://github.com/sunowsir" target="_blank">
				<i class="fa fa-github"></i>
			</a>
		</li>
			
</ul>

	</div>
		
	<div class="copyright">
		<p>
			 
				&copy;2019, content by sunowsir. All Rights Reserved.
			
			
			

	<!-- busuanzi -->
	<!-- busuanzi -->

		
	<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
	

		<span id="busuanzi_container_page_pv">
	  		本文总阅读量<span id="busuanzi_value_page_pv"></span>次
		</span>

	




		</p>
		<p>
			<a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a> Theme <a href="https://github.com/Sariay/hexo-theme-Annie" title="Annie" target="_blank" rel="noopener">Annie</a> by Sariay.
			<a href="javascript:zh_tran('s');" class="zh_click" id="zh_click_s">简体</a> 
			<a href="javascript:zh_tran('t');" class="zh_click" id="zh_click_t">繁體</a>				
		</p>
	</div>		
</footer>
		
	<!-- set '1' to show motto in all pages! -->

	<script src="/plugin/motto/motto.js"></script>
	
	<script type="text/javascript">
		$(".motto").html( getMingYanContent() );
	</script>	




	<!--
	时间：2018-10-3
	描述：
		插件名称：hexo-generator-search-zip
		插件来源: https://github.com/SuperKieran/hexo-generator-search-zip
		代码参考：https://github.com/SuperKieran/TKL/blob/master/layout/_partial/search.ejs(Include: js & css)	
-->
<div class="popup search-popup local-search-popup" >
	<div class="local-search-container">
		<span class="popup-btn-close">
      		ESC
   		</span>
		<div class="local-search-header">
			<div class="input-prompt">				
			</div>
			<input autocomplete="off" placeholder="Search..." type="text" id="local-search-input">
		</div>
		<div class="local-search-body">
			<div id="local-search-output"></div>
		</div>
		<div class="local-search-footer">
			<div class="topN-post">				
				
								
			</div>
		</div>
	</div>
</div>

<script src="/plugin/search/ziploader.js"></script>
<script src="/plugin/search/search.js"></script>

<script type="text/javascript">
	var search_path = 'search.json',
		zip_Path = '/search.zip',
		version_Path = '/searchVersion.txt',
		input_Trigger = 'auto',
		top_N = '2';

	themeLocalSearch({
		search_path, 
		zip_Path, 
		version_Path, 
		input_Trigger, 
		top_N
	});
</script>


<!-- love effect -->

	<script src="/plugin/love/love.js"></script>


<!-- back to top -->

	
	<div id="totop">
  		<a href="javascript:;"  name="TOTOP" class="fa fa-arrow-up" ></a>
	</div>




<!-- site analysis -->


	<!-- site-analysis -->
	
	
	
	
	
 

<script src="/plugin/vibrant/vibrant.js"></script>
<script src="/plugin/chinese/chinese.js"></script>
<script src="/plugin/imgLazyLoader/yall.min.js"></script>
<script src="/plugin/imgResize/jquery.resizeimagetoparent.min.js"></script>
<script src="/plugin/nicescroll/jquery.nicescroll.js"></script>
<script src="/js/resizediv.js"></script>
<script src="/js/main.js"></script><!-- hexo-inject:begin --><!-- Begin: Injected MathJax -->
<script type="text/x-mathjax-config">
  MathJax.Hub.Config("");
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
      all[i].SourceElement().parentNode.className += ' has-jax';
    }
  });
</script>

<script type="text/javascript" src="">
</script>
<!-- End: Injected MathJax -->
<!-- hexo-inject:end -->
	</body>	
</html>
